import permision from "@/js_sdk/wa-permission/permission.js"
import {ajax,ajaxGet,ajaxPost,showDialog,showToast} from '@/common/util.js'
import $store from '../store/index.js';
const getWxCode = () =>{
	return new Promise((resolve, reject) => {
		//得到code
		uni.login({
			provider: 'weixin',
			scopes: 'auth_base',
			success(req) {
				resolve(req.code)
			},
			fail(ero) {
				reject(ero);
			}
		})
	})
}

const getOpenId = () => {
	return new Promise((resolve, reject) => {
		getWxCode()
		.then(code=>{
			ajax('/api/businessUser/getBOpenId', {code})
				.then(res => {
					/*
						ifSave: false
						openid: "oJI2q5SZVsvzkcMlCv3AdFeP-RXA"
						userId: 1
					 */
					if (res) {
						resolve(res)
					} else {
						reject('得到用户openId失败,请重试')
					}
				}, eor => {
					reject(eor)
				})
		},err=>{})
	})
}
const getUserInfo=()=>{
	return new Promise((resolve,reject)=>{
		Promise.all([ajaxGet('/api/user/info'),ajaxGet('/api/user/getItem')]).then(res=>{
			let [{user,user:{activeItemId}},{itemList}]=res;
			user.itemList=itemList;
			if(!activeItemId){
				user.activeItemId=(itemList[0]||{}).id;
			}
			$store.commit('setUserInfo',user);
			resolve(user)
		},reject)
	})
}

const getDict=(dictType)=>{
	return new Promise((resolve,reject)=>{
		ajaxGet(`/dl/base/dict/${dictType}`,{}).then(res=>{
			resolve(res.map(v=>{
				return {name:v.dictLabel,val:v.dictValue}
			}))
		},reject)
	})
}

const getCurrentLocation=()=>{
	return new Promise((resolve,reject)=>{
		uni.getLocation({
			type:'gcj02',
			geocode:true,
			success:(data)=>{
				resolve(data)
			},
			fail(err) {
				console.log(err)
				// #ifdef APP
				showDialog('定位失败，请检查app是否已获取定位权限',{
					showCancel:true,
					confirmText:'授权设置',
					ok_cb:()=>{
						permision.gotoAppPermissionSetting();
					},
					no_cb:()=>{
						let tips='定位功能不能用';
						showToast(tips);
						reject(tips)
					},
				})
				// #endif
				reject(err)
			}
		})
	})
}
const getWeatherByCity=(city)=>{
	let url='https://query.asilu.com/weather/baidu?city='+city;
	return new Promise((resolve,reject)=>{
		uni.request({
			url,
			method:'GET',
			success: (res) => {
				let {data,data:{weather}}=res;
				resolve({city,list:weather})
			},
			fail: (err) => {
				console.log(err);
				reject(err)
			}
		})
	})
}
const getLocationWeather=()=>{
	return new Promise((resolve,reject)=>{
		getCurrentLocation().then(data=>{
			let {longitude,latitude,address}=data;
			let url=`https://query.asilu.com/weather/weather?longitude=${longitude}&latitude=${latitude}`;
			uni.request({
				url,
				method:'GET',
				success: (res) => {
					let {data,data:{city,list}}=res;
					//#ifdef APP
					city=address.city;
					//#endif
					if(!list){
						getWeatherByCity(city).then(resolve,reject)
					}else{
						resolve({city,list})
					}
				},
				fail: (err) => {
					console.log(err);
					reject(err)
				}
			})
		})
	})
}

const getMaintainAdmin=()=>{
	return new Promise((resolve,reject)=>{
		ajaxGet('/api/user/maintainAdminList').then(res=>{
			let list=res.map(v=>{
				return {realName:v.realName,name:`${v.realName}${v.companyName?'('+v.companyName+')':''}`,val:v.id}
			});
			resolve(list)
		},reject)
	})
}
const getMaintainUser=()=>{
	return new Promise((resolve,reject)=>{
		ajaxGet('/api/user/maintainUserList').then(res=>{
			let list=res.map(v=>{
				return {realName:v.realName,name:`${v.realName}${v.companyName?'('+v.companyName+')':''}`,val:v.id}
			});
			resolve(list)
		},reject)
	})
}
const getCheckUser=()=>{
	return new Promise((resolve,reject)=>{
		ajaxGet('/api/user/checkUserList').then(res=>{
			let list=res.map(v=>{
				return {name:v.realName,val:v.id}
			});
			resolve(list)
		},reject)
	})
}
const loginAndGetWxInfo=()=>{
	return new Promise((resolve,reject)=>{
		uni.login({
			provider:'weixin',
			scopes:'auth_user',
			success: (data) => {
				uni.getUserInfo({
					provider:'weixin',
					lang:'zh_CN',
					success: (res)=>{
						resolve(res.userInfo)
					},
					fail: (err) => {
						console.log(err)
					}
				})
			},
			fail: (err) => {
				console.log(err)
				reject(err)
			}
		})
	})
}
let problemTypes=[
	{name:'苗木',val:1,id:1,checked:true},
	{name:'病虫害',val:2,id:2,checked:false},
	{name:'整改问题',val:3,id:3,checked:false}
];
const getAppVersion=()=>{
	return new Promise(resolve=>{
		// #ifdef APP
		let {platform}=$store.state;//客户端平台，值域为：ios、android
		let version='v'+plus.runtime.version;//当前版本，值如 1.0.0
		$store.commit('setAppVersion',version);
		ajaxPost('/dl/base/getAppVersion',{data:{oldVersion:version},needToken:false}).then(res=>{
			resolve(res)
		},err=>{
			//showToast(err||'请求版本比对失败，请重试');
			resolve({version,status:3,updateFlag:0})
		})
		// #endif
		//updateFlag	是否最新版本(当为1时表示需要更新):0否1是
		//status	状态0强制升级1提示升级23不提示升级
	})
}

const checkNewUpdate=(showVersionTips=true)=>{
	return new Promise(((resolve,reject)=>{
		getAppVersion().then(res=>{
			let isNeedUpdate=res.status==0;
			let tips='有新版本，是否选择更新？';
			if(isNeedUpdate){
				tips='有新版本，请下载更新！'
			}
			if(res.updateFlag==1){// 提醒用户更新
				showDialog(tips,{
					title:'更新提示',
					showCancel:!isNeedUpdate,
					ok_cb(){
						plus.runtime.openURL(res.file);
					},
					no_cb(){
						reject()
					}
				})
			}else{
				showVersionTips&&showToast('当前已是最新版本');
				reject();
			}
		})
	}))
}
const getConfig=()=>{
	return ajaxGet('/h5/app/static/h5/config.json?t=111',{needToken:false})
}
const getCid=()=>{
	plus.push.getClientInfoAsync((info) => {
		let cid = info["clientid"];
		if(cid){
			$store.commit('setCid',cid)
		}else{
			setTimeout(()=>{
				getClientInfo()
			},200)
		}
	});
}

module.exports = {
	getOpenId,
	getUserInfo,
	getDict,
	getCurrentLocation,
	getLocationWeather,
	getMaintainAdmin,
	getMaintainUser,
	getCheckUser,
	loginAndGetWxInfo,
	problemTypes,
	getAppVersion,
	checkNewUpdate,
	getConfig,
	getCid,
}

